package com.msameer.gwttutor.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.editor.client.SimpleBeanEditorDriver;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.user.cellview.client.CellList;
import com.google.gwt.user.cellview.client.HasKeyboardSelectionPolicy.KeyboardSelectionPolicy;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SingleSelectionModel;
import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.msameer.gwttutor.server.Customer;

public class CustomerViewImpl extends Composite implements CustomerView {

	private static CustomerViewImplUiBinder uiBinder = GWT
			.create(CustomerViewImplUiBinder.class);
	
	@UiField Button btnSave;
	@UiField Button btnCancel;
	//@UiField VerticalPanel vPanel;
	@UiField CustomerEditor customerEditor;
	
	@UiField(provided=true) CellList<Customer> cellList = new CellList<Customer>(new AbstractCell<Customer>(){
		@Override
		public void render(Context context, Customer value, SafeHtmlBuilder sb) {
			sb.appendHtmlConstant("<b>");
			sb.appendEscaped(value.getId().toString());
			sb.appendHtmlConstant("</b><br/>");
			sb.appendEscaped(value.getName());
		}
	}, Customer.KEY_PROVIDER);
	
	interface CustomerViewImplUiBinder extends
			UiBinder<Widget, CustomerViewImpl> {
	}
	
	// Empty interface declaration, similar to UiBinder
	interface Driver extends SimpleBeanEditorDriver<Customer, CustomerEditor> {}
 
	// Create the Driver
	Driver driver = GWT.create(Driver.class);
    private Presenter presenter;
    private Integer id;
    //private Customer customer;

	//private boolean IsNew;
    
	public CustomerViewImpl() {
		initWidget(uiBinder.createAndBindUi(this));

	    cellList.setKeyboardSelectionPolicy(KeyboardSelectionPolicy.BOUND_TO_SELECTION);

	    // Add a selection model so we can select cells.
	    final SingleSelectionModel<Customer> selectionModel = new SingleSelectionModel<Customer>(
	        Customer.KEY_PROVIDER);
	    cellList.setSelectionModel(selectionModel);
	    selectionModel.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {
	      public void onSelectionChange(SelectionChangeEvent event) {
	    	  edit(selectionModel.getSelectedObject());
	        //contactForm.setContact(selectionModel.getSelectedObject());
	      }
	    });

		// Set the total row count. This isn't strictly necessary, but it affects
	    // paging calculations, so its good habit to keep the row count up to date.
	    cellList.setRowCount(Customer.getAll().size(), true);

	    // Push the data into the widget.
	    cellList.setRowData(0, Customer.getAll());		
	}

	@Override
	public void setId(Integer id) {
		this.id = id;
		if (id != null)
			edit(Customer.getAll().get(id));
		else 
			edit(new Customer());
	}

	@Override
	public void setPresenter(Presenter presenter) {
		this.presenter = presenter;
	}

	@UiHandler("btnSave")
	void onButtonClick(ClickEvent event) {
		save();
		// The presenter shall redirect to the URL of Customers page
        presenter.goTo(new CustomersPlace(""));
	}
	
	void edit(Customer customer) {
	    // PersonEditor is a DialogBox that extends Editor<Person>
	    //CustomerEditor editor = new CustomerEditor();
	    //vPanel.add(editor);
	    // Initialize the driver with the top-level editor
	    driver.initialize(customerEditor);
	    // Copy the data in the object into the UI
	    driver.edit(customer);
	}
	 
	// Called by some UI action
	void save() {
	    Customer edited = driver.flush();
	    if (driver.hasErrors()) {
	      // A sub-editor reported errors
	    }	    
	    if (IsNew())
	    	Customer.getAll().add(edited);
	    //doSomethingWithEditedPerson(edited);
	}

	private boolean IsNew() {
		// TODO Auto-generated method stub
		return id == null;
	}
	
}
